package com.onenine.app.listener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.text.TextUtils;

import com.onenine.app.activity.GroupMessageActivity;
import com.onenine.app.activity.PrivateMessageActivity;
import com.onenine.app.db.DataManager;
import com.onenine.app.event.GameChatEvent;
import com.onenine.app.event.MessageNotifyEvent;
import com.onenine.app.event.RecMessageEvent;
import com.onenine.app.model.FriendAddMessage;
import com.onenine.app.model.GameTextMessage;
import com.onenine.app.service.MessageQueueService;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.SpCommonHelper;
import com.onenine.app.view.MsgNotification;
import com.onenine.chat.model.LGroup;
import com.onenine.chat.model.LUser;
import com.onenine.chat.rongcloud.GroupCacheMgr;
import com.onenine.chat.rongcloud.RcImMgr;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.chat.rongcloud.UserCacheMgr;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.Logger;

import org.greenrobot.eventbus.EventBus;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.GroupNotificationMessage;
import io.rong.message.ImageMessage;
import io.rong.message.InformationNotificationMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

/**
 * 创建时间：2018/6/1 0001 13:18
 * 创建人：fly
 * 功能描述：消息接收器，包含融云和友盟推送
 */
public class OnMessageReceiveListener implements RongIMClient.OnReceiveMessageListener {

    private static final String VOICE_MESSAGE = "[语音]";
    private static final String IMAGE_MESSAGE = "[图片]";
    private Vibrator mVibrator;

    public OnMessageReceiveListener() {
    }

    @Override
    public boolean onReceived(final Message message, int i) {
        MessageContent messageContent = message.getContent();
        Logger.e("Receive a RongCloud's Message：" + message + "," + i);
        boolean isNotify = true;
        if (messageContent instanceof FriendAddMessage) {
            //收到好友通知消息
            FriendAddMessage friendAddMessage = ((FriendAddMessage) messageContent);
            if (friendAddMessage.getStatus() == DataType.FRIEND_APPLY) {
                //缓存新朋友的好友申请消息
                DataManager.saveOrUpdateNewFriendMessageByUserId(RcUser.getInstance().getUserId(), message.getSenderUserId()
                        , friendAddMessage.getContent());
                //统计未读消息数并post
                CDataProcessor.postNewFriendMsgUnreadCount();
                CDataProcessor.insertFriendMessageAfterDeleteAll(message);
            } else if (friendAddMessage.getStatus() == DataType.FRIEND_ALLOW) {
                //已成为好友
                CDataProcessor.syncFriendIds();
            } else {
                CDataProcessor.insertFriendMessageAfterDeleteAll(message);
            }
            postShowMsgRedPoint(DataType.GREET_NOTIFY_MSG);
            isNotify = false;
        } else if (messageContent instanceof GroupNotificationMessage) {
            //收到群组消息
            GroupNotificationMessage groupNtf = (GroupNotificationMessage) messageContent;
            if ((TextUtils.equals(groupNtf.getOperation(), GroupNotificationMessage.GROUP_OPERATION_DISMISS))) {
                //群组解散
                RcImMgr.getInstance().deleteConversation(message.getConversationType()
                        , groupNtf.getData());
            }
            EventBus.getDefault().post(messageContent);
            isNotify = false;
        } else if (messageContent instanceof InformationNotificationMessage) {
            //群拉人或踢人或修改名称,移除群聊缓存
            GroupCacheMgr.getInstance().deleteGroupCacheByGroupId(message.getTargetId());
            EventBus.getDefault().post(messageContent);
            isNotify = false;
        } else if (message.getConversationType() == Conversation.ConversationType.PRIVATE) {
            if (messageContent instanceof GameTextMessage) {
                //游戏聊天
                MessageQueueService.beginMessageService(ApUtils.getApp()
                        , new GameChatEvent(false, ((GameTextMessage) messageContent).getContent()));
                startNewMessageVibrator();
                return true;
            } else if (!DataManager.isMyFriend(message.getSenderUserId())) {
                //非好友的打招呼消息
                String content = "";
                if (messageContent instanceof TextMessage) {
                    content = ((TextMessage) messageContent).getContent();
                } else if (messageContent instanceof ImageMessage) {
                    content = IMAGE_MESSAGE;
                } else if (messageContent instanceof VoiceMessage) {
                    content = VOICE_MESSAGE;
                }
                DataManager.saveOrUpdateNewFriendMessageByUserId(RcUser.getInstance().getUserId()
                        , message.getSenderUserId(), content);
                postShowMsgRedPoint(DataType.GREET_NOTIFY_MSG);
                isNotify = false;
            }
        }
        EventBus.getDefault().post(new RecMessageEvent(message, i));
        if (isNotify) {
            isNotify = isJustNotify(message.getConversationType());
        }
        if (isNotify) {
            notifyMessageReceive(message);
        }
        return true;
    }

    /**
     * 当天是否处于正在聊天
     *
     * @param type
     * @return
     */
    private boolean isJustNotify(Conversation.ConversationType type) {
        boolean result = true;
        Activity topActivity = ActivityUtils.getTopActivity();
        if (topActivity != null) {
            if (type == Conversation.ConversationType.PRIVATE) {
                result = !TextUtils.equals(topActivity.getClass()
                        .getSimpleName(), PrivateMessageActivity.class.getSimpleName());
            } else if (type == Conversation.ConversationType.GROUP) {
                result = !TextUtils.equals(topActivity.getClass()
                        .getSimpleName(), GroupMessageActivity.class.getSimpleName());
            }
        }
        return result;
    }

    /**
     * 消息通知提醒
     */
    private void postShowMsgRedPoint(int type) {
        EventBus.getDefault().post(new MessageNotifyEvent(type));
    }


    /**
     * 开始新消息振动
     */
    private void startNewMessageVibrator() {
        if (mVibrator == null) {
            mVibrator = (Vibrator) ApUtils.getApp().getSystemService(Context.VIBRATOR_SERVICE);
        } else {
            mVibrator.cancel();
        }
        mVibrator.vibrate(new long[]{200, 100, 200, 100}, -1);
    }

    /**
     * 通知消息接收
     *
     * @param message 消息体
     */
    private void notifyMessageReceive(final Message message) {
        if (message.getConversationType() == Conversation.ConversationType.GROUP) {
            GroupCacheMgr.getInstance().getGroupAsync(message.getTargetId(), new GroupCacheMgr.OnGroupCallback() {
                @Override
                public void callback(LGroup group) {
                    if (group.getNoDisturb() > 0) {
                        Logger.e("该群聊处于免打扰状态:" + group);
                        return;
                    }
                    postShowMsgRedPoint(DataType.COMMON_NOTIFY_MSG);
                    if (!SpCommonHelper.getInstance().isIgnoreMsgNotify()) {
                        startNewMessageVibrator();
                        showNotification(message, group.getGroupId(), group.getGroupName());
                    }
                }
            });
        } else {
            UserCacheMgr.getInstance().getUserAsync(message.getSenderUserId(), new UserCacheMgr.OnUserCallback() {
                @Override
                public void callback(LUser user) {
                    postShowMsgRedPoint(DataType.COMMON_NOTIFY_MSG);
                    if (!SpCommonHelper.getInstance().isIgnoreMsgNotify()) {
                        startNewMessageVibrator();
                        showNotification(message, user.getUserId(), user.getNickName());
                    }
                }
            });
        }

    }

    /**
     * 显示通知栏通知
     *
     * @param message    消息体
     * @param targetId   目标ID
     * @param targetName 目标名
     */
    private void showNotification(Message message, String targetId, String targetName) {
        Intent intent;
        if (message.getConversationType() == Conversation.ConversationType.GROUP) {
            intent = GroupMessageActivity.getNotificationIntent(ApUtils.getApp(), targetId, targetName);
        } else {
            intent = PrivateMessageActivity.getNotificationIntent(ApUtils.getApp(), targetId, targetName);
        }
        String content = "";
        if (message.getContent() instanceof TextMessage) {
            content = ((TextMessage) message.getContent()).getContent();
        } else if (message.getContent() instanceof VoiceMessage) {
            content = VOICE_MESSAGE;
        } else if (message.getContent() instanceof ImageMessage) {
            content = IMAGE_MESSAGE;
        } else if (message.getContent() instanceof FriendAddMessage) {
            content = ((FriendAddMessage) message.getContent()).getContent();
        }
        MsgNotification.MsgContent msgContent = new MsgNotification.MsgContent();
        msgContent.msgTitle = targetName;
        msgContent.msgDesc = content;
        msgContent.msgDate = message.getReceivedTime();
        new MsgNotification(ApUtils.getApp(), targetId)
                .setMsgIntent(intent)
                .setAutoCount()
                .setMsgContent(msgContent)
                .showNotification();
    }

}
